package com.ericsson.web.core;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class SessionData {

	private int userId;
	private String sid;
	private String token;

	public SessionData(int userId) {
		this.setUserId(userId);
		this.setSid(generateRandomId());
		this.setToken(generateRandomId());
	}

	private static final int RANDOM_LENGTH = 16;
	private static final String SHA1_PRNG = "SHA1PRNG";
	private static final SecureRandom SECURITY_RANDOM_INSTANCE;
	static {
		try {
			SECURITY_RANDOM_INSTANCE = SecureRandom.getInstance(SHA1_PRNG);
		} catch (NoSuchAlgorithmException e) {
			throw new Error(e);
		}
	}
	public static String generateRandomId() {
		byte random[] = new byte[16];
		String result = null;
		StringBuffer buffer = new StringBuffer();
		int resultLenBytes = 0;
		while (resultLenBytes < RANDOM_LENGTH) {
			SECURITY_RANDOM_INSTANCE.nextBytes(random);
			random = getDigest().digest(random);
			for (int j = 0; j < random.length && resultLenBytes < RANDOM_LENGTH; j++) {
				byte b1 = (byte) ((random[j] & 0xf0) >> 4);
				byte b2 = (byte) (random[j] & 0x0f);
				if (b1 < 10)
					buffer.append((char) ('0' + b1));
				else
					buffer.append((char) ('A' + (b1 - 10)));
				if (b2 < 10)
					buffer.append((char) ('0' + b2));
				else
					buffer.append((char) ('A' + (b2 - 10)));
				resultLenBytes++;
			}
		}
		result = buffer.toString();
		return (result);

	}
	public static java.security.MessageDigest getDigest() {
		java.security.MessageDigest digest = null;
		try {
			digest = java.security.MessageDigest.getInstance("MD5");
		} catch (java.security.NoSuchAlgorithmException f) {
			digest = null;
		}
		return digest;
	}
	
	public void setUserId(int userId) {
		this.userId = userId;
	}

	public int getUserId() {
		return userId;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	public String getSid() {
		return sid;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getToken() {
		return token;
	}
}
